<?php
namespace CongoOpenSDK;

require_once(dirname(__FILE__) . '/OpenApi.php');

class Pay {
    // 预下单
    public static function createCashStage($inputs) {
        $nesscessaryKeys = ['amount', 'merchantId', 'merchantOrderId', 'callbackUrl', 'notifyUrl'];
        $optionalKeys = ['orderCreateDateTime', 'uppAppId', 'SHRULE', 'applicationTypeCode', 'clientIp', 'extra', 'ipFlag', 'openid', 'period', 'periodUnit', 'productName'];

        $params = [];
        foreach ($nesscessaryKeys as $key) {
            if (!array_key_exists($key, $inputs)) {
                throw new \UnexpectedValueException("Missing " . $key);
            }
            $params[$key] = $inputs[$key];
        }

        foreach ($optionalKeys as $key) {
            if (array_key_exists($key, $inputs)) {
                $params[$key] = $inputs[$key];
            }
        }

        if (!array_key_exists('orderCreateDateTime', $params)) {
            $datetime = new \DateTime;
            $params['orderCreateDateTime'] = $datetime->format('Y-m-d H:i:s');
        }
        if (!array_key_exists('uppAppId', $params)) {
            $params['uppAppId'] = '123456';
        }

        return self::request($params, 'PAY_PATH_CREATE_CASH_STAGE');
    }

    // 订单操作(查询）
    public static function getCashStage($inputs) {
        if (!array_key_exists('merchantId', $inputs)) {
            throw new \UnexpectedValueException("Missing merchantId");
        }
        if (!array_key_exists('merchantOrderId', $inputs)) {
            throw new \UnexpectedValueException("Missing merchantOrderId");
        }
        $params = array(
            'merchantId' => $inputs['merchantId'],
            'merchantOrderId' => $inputs['merchantOrderId'],
        );

        return self::request($params, 'PAY_PATH_GET_CASH_STAGE');
    }

    // 订单操作(退款）
    public static function cashStageRefund($inputs) {
        $nesscessaryKeys = ['amount', 'merchantId', 'orderId', 'orderType', 'refundnotifyurl'];
        $optionalKeys = ['ipFlag', 'payNo', 'refundInfo']; // 'opFlowNo',

        $params = [];
        foreach ($nesscessaryKeys as $key) {
            if (!array_key_exists($key, $inputs)) {
                throw new \UnexpectedValueException("Missing " . $key);
            }
            $params[$key] = $inputs[$key];
        }

        foreach ($optionalKeys as $key) {
            if (array_key_exists($key, $inputs)) {
                $params[$key] = $inputs[$key];
            }
        }

        if (!array_key_exists('payNo', $params)) {
            # 父订单号
            $params['payNo'] = $params['orderId'];
        }

        return self::request($params, 'PAY_PATH_REFUND');
    }

    // 微信企业付款
    public static function cashStageWithdrawal($inputs) {
        $nesscessaryKeys = ['amount', 'merchantId', 'merchantOrderId', 'notifyUrl', 'openid', 'orderDate', 'payOrg', 'productDesc'];
        $optionalKeys = ['merAcDate', 'currency', 'clientIp', 'ipFlag'];

        $params = [];
        foreach ($nesscessaryKeys as $key) {
            if (!array_key_exists($key, $inputs)) {
                throw new \UnexpectedValueException("Missing " . $key);
            }
            $params[$key] = $inputs[$key];
        }

        foreach ($optionalKeys as $key) {
            if (array_key_exists($key, $inputs)) {
                $params[$key] = $inputs[$key];
            }
        }

        if (!array_key_exists('merAcDate', $params)) {
            // 商户会计日期 按格式YYYYMMDD可以与订单提交日期保持一致
            $params['merAcDate'] = $params['orderDate'];
        }
        if (!array_key_exists('currency', $params)) {
            $params['currency'] = 'RMB';
        }

        return self::request($params, 'PAY_PATH_WITHDRAWAL');
    }

    private static function request($params, $urlType) {
        $config = OpenApi::getConfig();
        $url = $config[$urlType];

        $merchantKey = $config['PAY_MERCHANT_KEY'];
        $params['hmac'] = self::sign($params, $merchantKey);

        $result = OpenApi::execute($params, $url, null, '0.0.1');
        return $result;
    }

    public static function sign($params, $key = '') {
        $params = OpenApi::paraFilterSign($params);
        ksort($params);
        $sign = OpenApi::buildParamStr($params);
        return md5($sign . $key);
    }
}
?>
